<?php

class spExportExcel
{
	// this one only workds with php version >= 5.1.0
	public function export()
	{
		$fileName = 'somefile.csv';
 
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header('Content-Description: File Transfer');
		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename={$fileName}");
		header("Expires: 0");
		header("Pragma: public");
		 
		$fh = @fopen( 'php://output', 'w' );
		 
		global $wpdb;
		$query = "SELECT * FROM ksprojects";
		$results = $wpdb->get_results( $query, ARRAY_A );
		 
		$headerDisplayed = false;
		 
		foreach ( $results as $data ) {
			// Add a header row if it hasn't been added yet
			if ( !$headerDisplayed ) {
				// Use the keys from $data as the titles
				fputcsv($fh, array_keys($data), ";");
				$headerDisplayed = true;
			}
		 
			// Put the data into the stream
			fputcsv($fh, $data, ";" );
		}
		// Close the file
		fclose($fh);
		// Make sure nothing else is sent, our file is done
		exit;
	}

	public function export_1()
	{
		//create query to select as data from your table
		$select = "SELECT * FROM ksprojects";

		//run mysql query and then count number of fields
		$export = mysql_query ( $select ) 
			   or die ( "Sql error : " . mysql_error( ) );
		$fields = mysql_num_fields ( $export );

		$header = "";
		
		//create csv header row, to contain table headers 
		//with database field names
		for ( $i = 0; $i < $fields; $i++ ) {
			$header .= mysql_field_name( $export , $i ) . ",";
		}

		//this is where most of the work is done. 
		//Loop through the query results, and create 
		//a row for each
		$data = "";
		while( $row = mysql_fetch_row( $export ) ) {
			$line = '';
			//for each field in the row
			foreach( $row as $value ) {
				//if null, create blank field
				if ( ( !isset( $value ) ) || ( $value == "" ) ){
					$value = ",";
				}
				//else, assign field value to our data
				else {
					$value = str_replace( '"' , '""' , $value );
					$value = '"' . $value . '"' . ",";
				}
				//add this field value to our row
				$line .= $value;
			}
			//trim whitespace from each row
			$data .= trim( $line ) . "\n";
		}
		//remove all carriage returns from the data
		$data = str_replace( "\r" , "" , $data );

		$file_name = "test";


		//create a file and send to browser for user to download
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: csv" . date("Y-m-d") . ".csv");
		header( "Content-disposition: filename=".$file_name.".csv");
		print "$header\n$data";

		exit();
	}
}

?>